package org.ruanjj.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class ReflectConstructorTest {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, ClassNotFoundException {
        Teacher u1 = Teacher.class.getDeclaredConstructor(String.class,int.class).newInstance("Tony",19);
        System.out.println(u1.getName());

        Class<?> aClass = Class.forName("org.ruanjj.reflect.Teacher");
        Teacher u2 = (Teacher) aClass.getDeclaredConstructor(String.class).newInstance("Tom");
        System.out.println(u2.getName());

        //反射可以构造函数，也可以给private的属性赋值以及修改值，即使是单例对象，也可以通过反射构造
        Field[] declaredFields = aClass.getDeclaredFields();
        declaredFields[0].setAccessible(true);
        declaredFields[0].set(u2,20);
        System.out.println(u2.getName()+":"+u2.getAge());
    }
}
